package com.db.adjust;

import android.content.TextUtils;
import android.net.Uri;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.db.utils.IpInfo;
import com.db.utils.LogUtil;
import com.db.utils.ProxyUtil;
import com.db.utils.Util;
import com.db.utils.okhttp.HttpClientUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.json.JSONException;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by uerceg on 03/04/2017.
 */

public class UtilNetworking {
    private static String userAgent;

    //todo need to hook
    public static void setUserAgent(String userAgent) {
        UtilNetworking.userAgent = userAgent;
    }

//    public static ResponseData createPOSTHttpsURLConnection(String urlString, ActivityPackage activityPackage, int queueSize,IpInfo.DataBean ipData,String iso) throws Exception {
//        DataOutputStream wr = null;
//
//        try {
//            URL url = new URL(urlString);
//            HttpsURLConnection connection = null;
//            if(ipData != null){
//                connection = (HttpsURLConnection)url.openConnection(ProxyUtil.createProxy(ipData));
//            }else {
//                connection = (HttpsURLConnection) url.openConnection();
//            }
//
//            Map<String, String> parameters = new HashMap<String, String>(activityPackage.getParameters());
//
////            IConnectionOptions connectionOptions = AdjustFactory.getConnectionOptions();
////            connectionOptions.applyConnectionOptions(connection, activityPackage.getClientSdk());
//            applyConnectionOptions(connection, activityPackage.getClientSdk());
//
//            extractEventCallbackId(parameters);
//            System.out.println("before buildAuthorizationHeader:"+parameters.toString());
//
//            String authorizationHeader = buildAuthorizationHeader(parameters,
//                    activityPackage.getActivityKind().toString());
//            System.out.println("authorizationHeader:" + authorizationHeader);
//            if (authorizationHeader != null) {
//                connection.setRequestProperty("Authorization", authorizationHeader);
//            }
//            showRequestProperties(connection);
//
//            connection.setRequestMethod("POST");
//            connection.setUseCaches(false);
//            connection.setDoInput(true);
//            connection.setDoOutput(true);
//
//            wr = new DataOutputStream(connection.getOutputStream());
//            wr.writeBytes(getPostDataString(parameters, queueSize,iso));
//
//            ResponseData responseData = readHttpResponse(connection, activityPackage);
//
//            return responseData;
//        } catch (Exception e) {
//            throw e;
//        } finally {
//            try {
//                if (wr != null) {
//                    wr.flush();
//                    wr.close();
//                }
//            } catch (Exception e) {}
//        }
//    }


    public static ResponseData createPOSTHttpsURLConnection(String urlString, ActivityPackage activityPackage, int queueSize, IpInfo.DataBean ipData, String iso, String ua) throws Exception {

        HttpRequest request = HttpRequest.post(urlString);
        if (ipData != null) {
            // 设置代理IP
            request.setProxy(ProxyUtil.createProxy(ipData));
        }
        Map<String, String> parameters = new HashMap<>(activityPackage.getParameters());
        // 请求头
        applyConnectionOptions(request, activityPackage.getClientSdk(), ua);
        extractEventCallbackId(parameters);
//        System.out.println("before buildAuthorizationHeader:" + parameters.toString());
        LogUtil.logApp("AuthorizationHeader", "before buildAuthorizationHeader:" + parameters.toString());
        String authorizationHeader = buildAuthorizationHeader(parameters,
                activityPackage.getActivityKind().toString());
//        System.out.println("authorizationHeader:" + authorizationHeader);
        LogUtil.logApp("AuthorizationHeader", "after authorizationHeader:" + authorizationHeader);
        if (authorizationHeader != null) {
            request.header("Authorization", authorizationHeader);
        }
        HttpResponse response = request.body(getPostDataString(parameters, queueSize, iso)).execute();
        ResponseData responseData = readHttpResponse(response, activityPackage);
        return responseData;
    }

    public static Map<String, Object> createPOSTHttpsURLConnection2(String uuid, String urlString, ActivityPackage activityPackage, IpInfo.DataBean ipData, String iso, String ua) throws Exception {

        Map<String, Object> reqDetails = new HashMap<>();
        Map<String, String> parameters = new HashMap<>(activityPackage.getParameters());

        // 构建请求头
        Map<String, String> headerAdjustMap = new HashMap<>();
        headerAdjustMap.put("Client-SDK", activityPackage.getClientSdk());
        if (!TextUtils.isEmpty(ua)) {
            headerAdjustMap.put("User-Agent", ua);
        }
        extractEventCallbackId(parameters);
//        LogUtil.logApp("createPOSTHttpsURLConnection2", "uuid:" + uuid + ", before buildAuthorizationHeader:" + parameters.toString());
        String authorizationHeader = buildAuthorizationHeader(parameters, activityPackage.getActivityKind().toString());
//        LogUtil.logApp("createPOSTHttpsURLConnection2", "uuid:" + uuid + ", after authorizationHeader:" + authorizationHeader);
        if (authorizationHeader != null) {
            headerAdjustMap.put("Authorization", authorizationHeader);
        }

        parameters.put("sent_at", Util.format(System.currentTimeMillis(), iso));

        // 发送请求
        String respString = HttpClientUtil.doPost(urlString, parameters, headerAdjustMap, ipData);

        reqDetails.put("headers", headerAdjustMap);
        reqDetails.put("params", parameters);
        reqDetails.put("result", respString);

        return reqDetails;
    }

    public static void showRequestProperties(HttpsURLConnection connection) {
        Map map = connection.getRequestProperties();
        System.out.println("RequestProperties:" + map);

    }

//    public static ResponseData createGETHttpsURLConnection(ActivityPackage activityPackage, String basePath, String baseUrl, IpInfo.DataBean ipData,String iso) throws Exception {
//        try {
//            Map<String, String> parameters = new HashMap<String, String>(activityPackage.getParameters());
//            extractEventCallbackId(parameters);
//            Uri uri = buildUri(activityPackage.getPath(), parameters, basePath, baseUrl,iso);
//            URL url = new URL(uri.toString());
//            HttpsURLConnection connection = null;
//            if(ipData != null){
//                connection = (HttpsURLConnection)url.openConnection(ProxyUtil.createProxy(ipData));
//            }else {
//                connection = (HttpsURLConnection) url.openConnection();
//            }
//            applyConnectionOptions(connection, activityPackage.getClientSdk());
//            String authorizationHeader = buildAuthorizationHeader(parameters, activityPackage.getActivityKind().toString());
//            System.out.println("authorizationHeader:" + authorizationHeader);
//            if (authorizationHeader != null) {
//                connection.addRequestProperty("Authorization", authorizationHeader);
//            }
//            connection.setRequestMethod("GET");
//            showRequestProperties(connection);
//            ResponseData responseData = readHttpResponse(connection, activityPackage);
//
//            return responseData;
//        } catch (Exception e) {
//            throw e;
//        }
//    }

    public static ResponseData createGETHttpsURLConnection(ActivityPackage activityPackage, String basePath, String baseUrl, IpInfo.DataBean ipData, String iso, String ua) throws Exception {
        Map<String, String> parameters = new HashMap<>(activityPackage.getParameters());
        extractEventCallbackId(parameters);
        Uri uri = buildUri(activityPackage.getPath(), parameters, basePath, baseUrl, iso);
        URL url = new URL(uri.toString());
        HttpRequest request = HttpRequest.get(url.toString());
        if (ipData != null) {
            request.setProxy(ProxyUtil.createProxy(ipData));
        }
        applyConnectionOptions(request, activityPackage.getClientSdk(), ua);
        String authorizationHeader = buildAuthorizationHeader(parameters, activityPackage.getActivityKind().toString());
//        System.out.println("authorizationHeader:" + authorizationHeader);
        LogUtil.logApp("AuthorizationHeader", "authorizationHeader:" + authorizationHeader);
        if (authorizationHeader != null) {
            request.header("Authorization", authorizationHeader);
        }
        HttpResponse response = request.execute();
        ResponseData responseData = readHttpResponse(response, activityPackage);

        return responseData;


//        try {
//            Map<String, String> parameters = new HashMap<String, String>(activityPackage.getParameters());
//            extractEventCallbackId(parameters);
//            Uri uri = buildUri(activityPackage.getPath(), parameters, basePath, baseUrl,iso);
//            URL url = new URL(uri.toString());
//            HttpsURLConnection connection = null;
//            if(ipData != null){
//                connection = (HttpsURLConnection)url.openConnection(ProxyUtil.createProxy(ipData));
//            }else {
//                connection = (HttpsURLConnection) url.openConnection();
//            }
//            applyConnectionOptions(connection, activityPackage.getClientSdk());
//            String authorizationHeader = buildAuthorizationHeader(parameters, activityPackage.getActivityKind().toString());
//            System.out.println("authorizationHeader:" + authorizationHeader);
//            if (authorizationHeader != null) {
//                connection.addRequestProperty("Authorization", authorizationHeader);
//            }
//            connection.setRequestMethod("GET");
//            showRequestProperties(connection);
//            ResponseData responseData = readHttpResponse(connection, activityPackage);
//            return responseData;
//        } catch (Exception e) {
//            throw e;
//        }
    }

    public static CloseableHttpResponse createGETHttpsURLConnection2(String uuid, ActivityPackage activityPackage, String baseUrl, IpInfo.DataBean ipData, String iso, String ua) throws Exception {
        Map<String, String> parameters = new HashMap<>(activityPackage.getParameters());

        // 构建请求头
        extractEventCallbackId(parameters);
        Map<String, String> headerAdjustMap = new HashMap<>();
        headerAdjustMap.put("Client-SDK", activityPackage.getClientSdk());
        headerAdjustMap.put("Content-Type", "application/x-www-form-urlencoded");
        if (!TextUtils.isEmpty(ua)) {
            headerAdjustMap.put("User-Agent", ua);
        }
//        LogUtil.logApp("createGETHttpsURLConnection2", "uuid:" + uuid + ", before buildAuthorizationHeader:" + parameters);
        String authorizationHeader = buildAuthorizationHeader(parameters, activityPackage.getActivityKind().toString());
//        LogUtil.logApp("createGETHttpsURLConnection2", "uuid:" + uuid + ", after authorizationHeader:" + authorizationHeader);
        if (authorizationHeader != null) {
            headerAdjustMap.put("Authorization", authorizationHeader);
        }

        parameters.put("sent_at", Util.format(System.currentTimeMillis(), iso));

        return HttpClientUtil.doGet(baseUrl, parameters, headerAdjustMap, ipData);
    }

    private static ResponseData readHttpResponse(HttpResponse response, ActivityPackage activityPackage) throws Exception {
        StringBuffer sb = new StringBuffer();
        Integer responseCode = null;
        ResponseData responseData = ResponseData.buildResponseData(activityPackage);
//        try {
        responseCode = response.getStatus();
        InputStream inputStream;
        if (responseCode >= 400) {
//                inputStream = connection.getErrorStream();
        } else {
//                inputStream = connection.getInputStream();
        }
//            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                sb.append(line);
//            }


//        }
//        catch (Exception e) {
//            throw e;
//        } finally {
//            if (connection != null) {
//                connection.disconnect();
//            }
//        }
        String stringResponse = response.body();

        if (responseCode == 429) {
            return responseData;
        }
        if (stringResponse == null || stringResponse.length() == 0) {
            return responseData;
        }
        JSONObject jsonResponse = null;
        try {
            jsonResponse = new JSONObject(stringResponse);
        } catch (JSONException e) {
            String message = Util.formatString("Failed to parse json response. (%s)", e.getMessage());
            responseData.message = message;
        }
        if (jsonResponse == null) {
            return responseData;
        }
        responseData.jsonResponse = jsonResponse;
        String message = jsonResponse.optString("message", null);
        responseData.message = message;
        responseData.timestamp = jsonResponse.optString("timestamp", null);
        responseData.adid = jsonResponse.optString("adid", null);
        String trackingState = jsonResponse.optString("tracking_state", null);
        if (trackingState != null) {
            if (trackingState.equals("opted_out")) {
                responseData.trackingState = TrackingState.OPTED_OUT;
            }
        }
        if (message == null) {
            message = "No message found";
        }
        if (responseCode != null && responseCode == HttpsURLConnection.HTTP_OK) {
            responseData.success = true;
        } else {
        }
        return responseData;
    }


    private static ResponseData readHttpResponse(HttpsURLConnection connection, ActivityPackage activityPackage) throws Exception {
        StringBuffer sb = new StringBuffer();
        Integer responseCode = null;
        ResponseData responseData = ResponseData.buildResponseData(activityPackage);
        try {
            connection.connect();
            responseCode = connection.getResponseCode();
            InputStream inputStream;
            if (responseCode >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        String stringResponse = sb.toString();

        if (responseCode == 429) {
            return responseData;
        }
        if (stringResponse == null || stringResponse.length() == 0) {
            return responseData;
        }
        JSONObject jsonResponse = null;
        try {
            jsonResponse = new JSONObject(stringResponse);
        } catch (JSONException e) {
            String message = Util.formatString("Failed to parse json response. (%s)", e.getMessage());
            responseData.message = message;
        }
        if (jsonResponse == null) {
            return responseData;
        }
        responseData.jsonResponse = jsonResponse;
        String message = jsonResponse.optString("message", null);
        responseData.message = message;
        responseData.timestamp = jsonResponse.optString("timestamp", null);
        responseData.adid = jsonResponse.optString("adid", null);
        String trackingState = jsonResponse.optString("tracking_state", null);
        if (trackingState != null) {
            if (trackingState.equals("opted_out")) {
                responseData.trackingState = TrackingState.OPTED_OUT;
            }
        }
        if (message == null) {
            message = "No message found";
        }
        if (responseCode != null && responseCode == HttpsURLConnection.HTTP_OK) {
            responseData.success = true;
        } else {
        }
        return responseData;
    }

    private static String getPostDataString(Map<String, String> body, int queueSize, String iso) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();

        for (Map.Entry<String, String> entry : body.entrySet()) {
            String encodedName = URLEncoder.encode(entry.getKey(), Constants.ENCODING);
            String value = entry.getValue();
            String encodedValue = value != null ? URLEncoder.encode(value, Constants.ENCODING) : "";

            if (result.length() > 0) {
                result.append("&");
            }

            result.append(encodedName);
            result.append("=");
            result.append(encodedValue);
        }

        long now = System.currentTimeMillis();
//        String dateString = Util.dateFormatter.format(now);
        String dateString = Util.format(now, iso);

        result.append("&");
        result.append(URLEncoder.encode("sent_at", Constants.ENCODING));
        result.append("=");
        result.append(URLEncoder.encode(dateString, Constants.ENCODING));

        if (queueSize > 0) {
            result.append("&");
            result.append(URLEncoder.encode("queue_size", Constants.ENCODING));
            result.append("=");
            result.append(URLEncoder.encode("" + queueSize, Constants.ENCODING));
        }

        return result.toString();
    }

    private static Uri buildUri(String path, Map<String, String> parameters, String basePath, String url, String iso) {
        Uri.Builder uriBuilder = new Uri.Builder();

        String scheme = Constants.SCHEME;
        String authority = Constants.AUTHORITY;
        String initialPath = "";

        try {
            if (basePath != null) {
                url += basePath;
            }
            URL baseUrl = new URL(url);
            scheme = baseUrl.getProtocol();
            authority = baseUrl.getAuthority();
            initialPath = baseUrl.getPath();
        } catch (MalformedURLException e) {
//            getLogger().error("Unable to parse endpoint (%s)", e.getMessage());
            System.out.println("Unable to parse endpoint (%s)" + e.getMessage());
        }

        uriBuilder.scheme(scheme);
        uriBuilder.encodedAuthority(authority);
        uriBuilder.path(initialPath);
        uriBuilder.appendPath(path);

        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
        }

        long now = System.currentTimeMillis();
//        String dateString = Util.dateFormatter.format(now);
        String dateString = Util.format(now, iso);

        uriBuilder.appendQueryParameter("sent_at", dateString);

        return uriBuilder.build();
    }

    private static String extractAppSecret(final Map<String, String> parameters) {
        return parameters.remove("app_secret");
    }

    private static String extractSecretId(final Map<String, String> parameters) {
        return parameters.remove("secret_id");
    }

    private static String extractSignature(final Map<String, String> parameters) {
        return parameters.remove("signature");
    }

    private static String extractAlgorithm(final Map<String, String> parameters) {
        return parameters.remove("algorithm");
    }

    private static String extractNativeVersion(final Map<String, String> parameters) {
        return parameters.remove("native_version");
    }

    private static String extractHeadersId(final Map<String, String> parameters) {
        return parameters.remove("headers_id");
    }

    private static void extractEventCallbackId(final Map<String, String> parameters) {
        parameters.remove("event_callback_id");
    }

    private static String extractAdjSigningId(final Map<String, String> parameters) {
        return parameters.remove("adj_signing_id");
    }

    /**
     * 构建认证头
     *
     * @param parameters
     * @param activityKind
     * @return
     */
    private static String buildAuthorizationHeader(final Map<String, String> parameters,
                                                   final String activityKind) {
        String adjSigningId = extractAdjSigningId(parameters);
        String secretId = extractSecretId(parameters);
        String headersId = extractHeadersId(parameters);
        String signature = extractSignature(parameters);
        String algorithm = extractAlgorithm(parameters);
        String nativeVersion = extractNativeVersion(parameters);

        String authorizationHeader = buildAuthorizationHeaderV2WithAdjSigningId(signature, adjSigningId,
                headersId, algorithm, nativeVersion);
        if (authorizationHeader != null) {
            LogUtil.logApp("AuthorizationHeader", "authorization from WithAdjSigningId");
            return authorizationHeader;
        }

        // 调用libsigner.so获取sign信息
        authorizationHeader = buildAuthorizationHeaderV2(signature, secretId, headersId, algorithm, nativeVersion);
        if (authorizationHeader != null) {
            LogUtil.logApp("AuthorizationHeader", "authorization from secretID");
            return authorizationHeader;
        }
        LogUtil.logApp("AuthorizationHeader", "authorization from V1");
        String appSecret = extractAppSecret(parameters);

        // 如果获取libsigner.so失败，拼装其他参数再返回
        return buildAuthorizationHeaderV1(parameters, appSecret, secretId, activityKind);
    }

    private static String buildAuthorizationHeaderV1(final Map<String, String> parameters,
                                                     final String appSecret,
                                                     final String secretId,
                                                     final String activityKind) {
        // check if the secret exists and it's not empty
        if (appSecret == null || appSecret.length() == 0) {
            return null;
        }
        String appSecretName = "app_secret";

        Map<String, String> signatureDetails = getSignature(parameters, activityKind, appSecret);

        String algorithm = "sha256";
        String signature = Util.sha256(signatureDetails.get("clear_signature"));
        String fields = signatureDetails.get("fields");

        String secretIdHeader = Util.formatString("secret_id=\"%s\"", secretId);
        String signatureHeader = Util.formatString("signature=\"%s\"", signature.toUpperCase());
        String algorithmHeader = Util.formatString("algorithm=\"%s\"", algorithm);
        String fieldsHeader = Util.formatString("headers=\"%s\"", fields);

        String authorizationHeader = Util.formatString("Signature %s,%s,%s,%s",
                secretIdHeader, signatureHeader, algorithmHeader, fieldsHeader);

        return authorizationHeader;
    }

    private static String buildAuthorizationHeaderV2(final String signature,
                                                     final String secretId,
                                                     final String headersId,
                                                     final String algorithm,
                                                     final String nativeVersion) {
        if (secretId == null || signature == null || headersId == null) {
            return null;
        }

        String signatureHeader = Util.formatString("signature=\"%s\"", signature.toUpperCase());
        String secretIdHeader = Util.formatString("secret_id=\"%s\"", secretId);
        String idHeader = Util.formatString("headers_id=\"%s\"", headersId);
        String algorithmHeader = Util.formatString("algorithm=\"%s\"", algorithm != null ? algorithm : "adj1");
        String nativeVersionHeader = Util.formatString("native_version=\"%s\"", nativeVersion != null ? nativeVersion : "");

        String authorizationHeader = Util.formatString("Signature %s,%s,%s,%s,%s",
                signatureHeader, secretIdHeader, algorithmHeader, idHeader, nativeVersionHeader);

//        getLogger().verbose("authorizationHeader: %s", authorizationHeader);
//        System.out.printf("authorizationHeader: %s", authorizationHeader);

        return authorizationHeader;
    }


    private static String buildAuthorizationHeaderV2WithAdjSigningId(final String signature,
                                                                     final String adjSigningId,
                                                                     final String headersId,
                                                                     final String algorithm,
                                                                     final String nativeVersion) {
        if (adjSigningId == null || signature == null || headersId == null) {
            return null;
        }

        String signatureHeader = Util.formatString("signature=\"%s\"", signature.toUpperCase());
        String adjSigningIdHeader = Util.formatString("adj_signing_id=\"%s\"", adjSigningId);
        String idHeader = Util.formatString("headers_id=\"%s\"", headersId);
        String algorithmHeader = Util.formatString("algorithm=\"%s\"", algorithm != null ? algorithm : "adj1");
        String nativeVersionHeader = Util.formatString("native_version=\"%s\"", nativeVersion != null ? nativeVersion : "");

        String authorizationHeader = Util.formatString("Signature %s,%s,%s,%s,%s",
                signatureHeader, adjSigningIdHeader, algorithmHeader, idHeader, nativeVersionHeader);


        return authorizationHeader;
    }

    private static Map<String, String> getSignature(final Map<String, String> parameters,
                                                    final String activityKind,
                                                    final String appSecret) {
        String activityKindName = "activity_kind";
        String activityKindValue = activityKind;

        String createdAtName = "created_at";
        String createdAt = parameters.get(createdAtName);

        String deviceIdentifierName = getValidIdentifier(parameters);
        String deviceIdentifier = parameters.get(deviceIdentifierName);

        String sourceName = "source";
        String sourceValue = parameters.get(sourceName);

        String payloadName = "payload";
        String payloadValue = parameters.get(payloadName);

        Map<String, String> signatureParams = new HashMap<String, String>();

        signatureParams.put("app_secret", appSecret);
        signatureParams.put(createdAtName, createdAt);
        signatureParams.put(activityKindName, activityKindValue);
        signatureParams.put(deviceIdentifierName, deviceIdentifier);

        if (sourceValue != null) {
            signatureParams.put(sourceName, sourceValue);
        }

        if (payloadValue != null) {
            signatureParams.put(payloadName, payloadValue);
        }

        String fields = "";
        String clearSignature = "";

        for (Map.Entry<String, String> entry : signatureParams.entrySet()) {
            if (entry.getValue() != null) {
                fields += entry.getKey() + " ";
                clearSignature += entry.getValue();
            }
        }

        // Remove last empty space.
        fields = fields.substring(0, fields.length() - 1);

        HashMap<String, String> signature = new HashMap<String, String>();

        signature.put("clear_signature", clearSignature);
        signature.put("fields", fields);

        return signature;
    }

    private static String getValidIdentifier(final Map<String, String> parameters) {

        String idfaName = "idfa";
        String idfvName = "idfv";
        String googleAdIdName = "gps_adid";
        String fireAdIdName = "fire_adid";
        String androidIdName = "android_id";
        String macSha1Name = "mac_sha1";
        String macMd5Name = "mac_md5";
        String androidUUIDName = "android_uuid";

        if (parameters.get(idfaName) != null) {
            return idfaName;
        }
        if (parameters.get(idfvName) != null) {
            return idfvName;
        }
        if (parameters.get(googleAdIdName) != null) {
            return googleAdIdName;
        }
        if (parameters.get(fireAdIdName) != null) {
            return fireAdIdName;
        }
        if (parameters.get(androidIdName) != null) {
            return androidIdName;
        }
        if (parameters.get(macSha1Name) != null) {
            return macSha1Name;
        }
        if (parameters.get(macMd5Name) != null) {
            return macMd5Name;
        }
        if (parameters.get(androidUUIDName) != null) {
            return androidUUIDName;
        }

        return null;
    }

    public interface IConnectionOptions {
        void applyConnectionOptions(HttpsURLConnection connection, String clientSdk);
    }

    public static void applyConnectionOptions(HttpsURLConnection connection, String clientSdk) {
        connection.setRequestProperty("Client-SDK", clientSdk);
        //todo need to be check
        connection.setConnectTimeout(Constants.ONE_MINUTE);
        connection.setReadTimeout(Constants.ONE_MINUTE);

        if (userAgent != null) {
            connection.setRequestProperty("User-Agent", userAgent);
        }
    }

    public static void applyConnectionOptions(HttpRequest request, String clientSdk, String ua) {
        request.header("Client-SDK", clientSdk);
        if (!TextUtils.isEmpty(ua)) {
            request.header("User-Agent", ua);
        }
        request.setConnectionTimeout(Constants.ONE_MINUTE);
        request.setReadTimeout(Constants.ONE_MINUTE);
    }

    public static void main(String[] args) {
//        HttpRequest request = HttpRequest.post("http://www.baidu.com");
//        request.header("Client-SDK", "sdk223333");
//        request.header("Authorization", "asdfasfasdf");
//        HttpResponse response = request.body("adfasdfddd").execute();

        DataOutputStream wr = null;
        try {
            URL url = new URL("http://www.baidu.com");
            HttpURLConnection connection = null;
            connection = (HttpURLConnection) url.openConnection();
//            IConnectionOptions connectionOptions = AdjustFactory.getConnectionOptions();
//            connectionOptions.applyConnectionOptions(connection, activityPackage.getClientSdk());
            connection.setRequestProperty("Client-SDK", "adfasdfasdf");
            connection.setRequestProperty("Authorization", "059924245");
            System.out.println(connection.getRequestProperties());
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes("adfadf");
            wr.flush();
            connection.connect();
            int responseCode = connection.getResponseCode();
            InputStream inputStream;
            if (responseCode >= 400) {
                inputStream = connection.getErrorStream();
            } else {
                inputStream = connection.getInputStream();
            }
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (wr != null) {
                    wr.flush();
                    wr.close();
                }
            } catch (Exception e) {
            }
        }


    }
}
